#include"../include/map.h"

void put(void *self, void *key, void *value) {  
    Map *map=(Map*)self;
    RBTreeNode *node = search(map->tree, key);  
    if (node != NULL) {  
        node->value = value; // 更新现有值  
    } else {  
        RB_insert(map->tree, key, value); // 插入新键值对  
    }  
    return;
}  

void* map_get(void *self, void *key) {  
    Map *map=(Map*)self;
    RBTreeNode *node = search(map->tree, key);  
    return node != NULL ? node->value : NULL; // 返回找到的值或 NULL  
}  

void map_erase(void *self, void *key) {  
    Map *map=(Map*)self;
    delete_node(map->tree, key);  
}  

void map_clear(void *self) {  
    Map *map=(Map*)self;
    free(map->tree); // 这里应添加释放树节点的完整代码  
    free(map);  
}  

// 将 Map 转换为数组  
Array* map_data(void *self) {  
    Map *map=(Map*)self;
    return tree_to_array(map->tree);  
}

Map* map(int (*compare)(const void *, const void *)) {  
    Map *map = malloc(sizeof(Map));  
    map->tree = malloc(sizeof(RBTree));  
    map->tree->root = NULL;  
    map->tree->compare = compare;  
    map->tree->size = 0;  
    map->clear=map_clear;
    map->data=map_data;
    map->erase=map_erase;
    map->get=map_get;
    map->put=put;
    return map;  
}  
